<template>
	<LayoutFull :enableHeader="false" :enableAside="false">
		<template #main>
			<vxe-grid
				ref="tableRef"
				:="tableAttrs"
				:data="tableState.pageData"
				:columns="tableState.columns"
				:pagerConfig="tablePager"
				@page-change="tablePageChange"
				@edit-closed="tableEditClosed"
			>
				<template #toolbar_left>
					<div style="padding-left: 8px;">
						<el-button type="primary" plain @click="toolbarOperate('import')">导入数据</el-button>
						<el-button type="primary" plain @click="toolbarOperate('save')">保存数据</el-button>
						<el-button type="primary" plain @click="toolbarOperate('view')">查看数据</el-button>
					</div>
				</template>
				<template #toolbar_right></template>
				<template #input_edit="{ row, column }">
					<el-input placeholder="请输入内容" clearable v-model="row[column.field]" />
				</template>
				<template #operation="{ row }">
					<el-button type="primary" link @click="tableRowOperate('edit', row)">编辑</el-button>
				</template>
			</vxe-grid>
		</template>
	</LayoutFull>
</template>
<script setup>
import { ElMessage } from 'element-plus';
import { onBeforeMount, onMounted, reactive, ref, toRaw } from 'vue';

// 表格的Ref
const tableRef = ref()
// 表格属性配置
const tableAttrs = reactive({
	size: 'small',
	border: true,
	height: 'auto',
	loading: false,
	keepSource: true,
	headerAlign: 'center',
	showOverflow: true,
	// 虚拟滚动X轴
	scrollX: { enabled: true },
	// 虚拟滚动Y轴
	scrollY: { enabled: true },
	// 行属性配置
	rowConfig: {
		// 当鼠标移到行时，是否要高亮当前行
		isHover: true,
		// 自定义行数据唯一主键的字段名（默认自动生成）
		keyField: 'fieldId',
		// 当鼠标点击行时，是否要高亮当前行
		isCurrent: true,
	},
	// 编辑配置
	editConfig: {
		icon: 'fa fa-pencil-square-o',
		mode: 'row',
		enabled: true,
		trigger: 'click',
		showStatus: true,
		showUpdateStatus: true,
	},
	// 列属性配置
	columnConfig: {
		// 每一列是否启用列宽调整
		resizable: true,
	},
	// 工具栏配置
	toolbarConfig: {
		// 是否允许最大化
		zoom: true,
		// 打印按钮配置
		print: false,
		// 导入按钮配置（需要设置 "import-config"）
		import: false,
		// 导出按钮配置（需要设置 "export-config"）
		export: false,
		// 自定义列配置
		custom: false,
		// 是否开启
		enabled: true,
		// 刷新
		refresh: true,
		// 是否加载中
		loading: false,
		// 给工具栏 className
		className: 'rk-grid-toolbar',
		// 插槽配置
		slots: {
			// 右侧工具列表
			tools: 'toolbar_right',
			// 按钮列表
			buttons: 'toolbar_left',
		},
	},
	// 序号配置
	seqConfig: {
		seqMethod: ({ rowIndex }) => {
			return (tablePager.currentPage - 1) * tablePager.pageSize + (rowIndex + 1)
		}
	},
	rowClassName: ({ row, rowIndex }) => {
		if (tableState.editData.find(item => item.fieldId === row.fieldId)) {
			return 'update-row--dirty'
		} else {
			return ''
		}
	},
	// 单元格样式配置
	cellClassName: ({ row, rowIndex, column }) => {
		let index = (tablePager.currentPage - 1) * tablePager.pageSize + (rowIndex)
		let cacheRow = tableState.cacheData[index]
		const newValue = row[column.field]
		const oldValue = cacheRow[column.field]
		return (newValue !== oldValue) ? 'update-cell--dirty' : ''
	}
})
// 表格分页配置
const tablePager = reactive({
	total: 0,
	border: true,
	enabled: true,
	layouts: ['Sizes', 'PrevJump', 'PrevPage', 'JumpNumber', 'NextPage', 'NextJump', 'FullJump', 'Total'],
	pageSize: 1000,
	pageSizes: [1000, 1500, 2000],
	className: 'rk-grid-pager',
	background: true,
	currentPage: 1,
})
// 表格数据集配置
const tableState = reactive({
	// 表格配置数据
	columns: [],
	// 编辑更新的数据
	editData: [],
	// 全量数据
	fullData: [],
	// 当前分页数据
	pageData: [],
	// 全量缓存数据
	cacheData: [],
	// 字段数据数组（mock出来的）
	dataFields: [],
})

/**
 * 工具栏操作
 * 
 * @param type 类型
 */
const toolbarOperate = (type) => {
	switch (type) {
		case 'add':
			handleAddRow()
      break;
		case 'del':
			handleDelRow()
      break;
		case 'edit':
			handleEditRow()
      break;
		case 'view':
			handleViewData()
      break;
		case 'save':
			handleSaveData()
      break;
		case 'import':
			handleImportData()
      break;
		default:
			break;
	}
}
/**
 * 表格行操作
 * 
 * @param type 类型
 * @param row 行数
 */
const tableRowOperate = (type, row) => {
	console.log('tableRowOperate', JSON.parse(JSON.stringify({ type, row })))
	switch (type) {
		case 'edit':
			handleEditRow(row)
      break;
		default:
			break;
	}
}
/**
 * 新增行数据
 */
const handleAddRow = () => {
	const record = {
		i: +new Date(),
		field1: '新增行',
		field2: '新增行',
	}
	tableRef.value.insertAt(record);
}
/**
 * 删除数据
 */
const handleDelRow = () => {
	tableRef.value.removeCheckboxRow();
}
/**
 * 设置行编辑
 * @param row 行数据
 */
const handleEditRow = (row) => {
	tableRef.value.setEditRow(row);
}
/**
 * 查看数据
 */
const handleViewData = () => {
	const tableInfo = tableRef.value.getTableData()
	console.log('getTableData', {
		tableInfo, tableState: toRaw(tableState)
	})
}
/**
 * 保存数据
 */
const handleSaveData = () => {
	const { editData } = tableState
	if (editData.length === 0) {
		ElMessage.warning('数据未做更改，请确认！')
	} else {
		ElMessage.success(`共有${editData.length}条数据发生了变化，请确认！`)
	}
}
/**
 * 导入数据
 */
const handleImportData = () => {
	loadFullData()
	loadPageData()
	
}

/**
 * 编辑结束触发
 * 
 * @param info 参数信息
 */
const tableEditClosed = (info) => {
	const { row, column } = info
	const { editData, fullData, cacheData } = tableState
	console.log('tableEditClosed', { editData, fullData, info })
	const cacheRow = cacheData.find(item => item.fieldId === row.fieldId)
	const editIndex = tableState.editData.findIndex(item => item.fieldId === row.fieldId)
	if (editIndex === -1) {
		if (cacheRow[column.field] === row[column.field]) {
			console.warn('数据与原始一致，不做数据的缓存！')
			return
		}
		tableState.editData.push(JSON.parse(JSON.stringify(row)))
	} else {
		const editOldRow = editData[editIndex]
		if (editOldRow[column.field] === row[column.field]) {
			console.warn('数据未发生变化，不做数据的更新！')
			return
		}
		if (cacheRow[column.field] === row[column.field]) {
			console.warn('数据与原始一致，将数据从编辑数组中删除！')
			tableState.editData.splice(editIndex, 1)
			return
		}
		tableState.editData[editIndex] = JSON.parse(JSON.stringify(row))
	}
}
/**
 * 分页变化触发
 * @param param 参数
 */
const tablePageChange = ({ pageSize, currentPage }) => {
	tablePager.pageSize = pageSize
	tablePager.currentPage = currentPage
	loadPageData()
}

const loadColumns = () => {
	const columns = [
		// 序号列
		{ type: 'seq', width: 68, title: '序号', align: 'center', fixed: 'left', headerAlign: 'center', }
	]
	const dataFields = []
	for (let i = 1; i <= 30; i++) {
		const field = `field${i}`
		const colItem = {
			field,
			title: `字段${i}`,
			width: 200,
			align: 'left',
			slots: { edit: 'input_edit' },
			editRender: { autofocus: '.el-input__inner' },
			headerAlign: 'center',
		}
		columns.push(colItem)
		dataFields.push(field)
	}
	// // 设置操作列
	// columns.push({
	// 	field: 'operation',
	// 	title: `操作`,
	// 	width: 100,
	// 	align: 'center',
	// 	fixed: 'right',
	// 	sortable: false,
	// 	slots: { default: 'operation' }
	// })
	tableState.columns = columns
	tableState.dataFields = dataFields
}
const loadFullData = () => {
	let data = []
	for (let i = 1; i <= 56000; i++) {
		let row = { fieldId: i }
		for (let field of tableState.dataFields) {
			row[field] = `值${i}-${field}`
		}
		data.push(row)
	}
	tablePager.total = data.length
	tableState.fullData = data
	tableState.cacheData = JSON.parse(JSON.stringify(data))
}
const loadPageData = () => {
	tableAttrs.loading = true;
	const { pageSize, currentPage } = tablePager;
	const start = (currentPage - 1) * pageSize;
	const end = start + pageSize;
	tableState.pageData = tableState.fullData.slice(start, end);
	tableAttrs.loading = false;
}

onBeforeMount(() => {
	loadColumns()
})

</script>

<style lang="scss">
.update-cell--dirty {
	&::before {
		content: "";
    top: calc(var(--vxe-table-cell-dirty-width)* -1);
    left: calc(var(--vxe-table-cell-dirty-width)* -1);
    position: absolute;
    border-width: var(--vxe-table-cell-dirty-width);
    border-style: solid;
    border-color: transparent var(--vxe-table-cell-dirty-update-color) transparent transparent;
    transform: rotate(45deg);
	}
}
.update-row--dirty {
	background-color: #e6f7ff;
}
</style>
<style lang="scss" scoped>
.common-form-layout {
  &__wrapper {
    height: 100%;
    display: flex;
    flex-direction: column;
  }
  &__body {
    flex: 1;
    background: #fff;
    min-height: 100px;
  }
}
</style>
